<template>
  <div style="height: 100%;" v-if="this.columnFinalData.length>0">
    <el-table class="root-table" v-el-table-infinite-scroll="loadTableData" infinite-scroll-disabled="disabledMore"
      ref="tableGrid" :data="reqData.tableData" border @cell-mouse-enter="tableRowEnter"
      @cell-mouse-leave="tableRowLeave" @select-all="tableSelectAll" :row-style="rowStyle"
      @header-dragend="headerDragend" :fit="true" height="100%">
      <el-table-column type="selection" width="60" v-if="columnFinalData.length>0" align="left" :key="-100">
        <template slot-scope="scope">
          <span v-if="(scope.row.isHover||scope.row.isSelected)&&!scope.row.isLocked">
            <el-checkbox v-model="scope.row.isSelected" @change="(data) => {tableRowSelect(scope.row, data)}">
            </el-checkbox>
          </span>
          <span v-else>{{scope.row.rowIndex}}</span>
        </template>
      </el-table-column>
      <el-table-column :width="getColumnWidth(item.name,1,index)" v-if="item.visibile"
        v-for="(item, index) in columnFinalData" :key="index" :prop="item.name" :label="item.label"
        :align="getColumnAlign(item)" :fixed="item.isFixed" show-overflow-tooltip>
        <template slot="header" slot-scope="scope">
          <span>{{scope.column.label}}</span>
          <span class="my-lock-column" v-if="item.isFixed">
            <svg-icon icon-class="icon-lock-column" />
          </span>
          <span v-if="item.fieldRemark">
            <el-tooltip class="item" effect="dark" :content="item.fieldRemark" placement="top">
              <i class="el-icon-warning"></i>
            </el-tooltip>
          </span>
        </template>
        <template slot-scope="scope">
          <span v-html="getMyFormatValueHtml(scope)"></span>
          <!-- <span @click="handleClickCommentCount(scope.row)" class="column-comment-count"
            v-if="index==0&&scope.row['commentCount']">
            <svg-icon icon-class="icon-comment" />
            <span class="column-comment-count-number">{{scope.row['commentCount']}}</span>
          </span>
          <span @click="handleClickRemind(scope,$event)" class="column-remind-count"
            v-if="index==0&&scope.row['remindCount']">
            <svg-icon icon-class="icon-remind" />
          </span> -->
          <span class="column-right-fixed" v-if="index==0&&(scope.row['commentReindCount']||scope.row.isLocked)">
            <span v-if="scope.row.isLocked">
              <svg-icon icon-class="icon-lock" />
            </span>
            <span @click="doEdit(scope.row.Id)"
              v-bind:class="'column-right-number-fixed column-right-number-fixed_'+scope.row['lastLogType']"
              style="position: relative;" v-if="scope.row['commentReindCount']">
              <svg-icon v-if="scope.row['lastLogType']==2" icon-class="icon-number-bg" />
              <svg-icon v-else icon-class="icon-remind" />
              <span class="column-comment-count-number">{{scope.row['commentReindCount']}}</span>
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column class-name="last-column" v-if="moreColumnVisible()" :key="99999">
      </el-table-column>
    </el-table>
    <p class="bottom-loading" v-if="loadingMore">加载中...</p>
    <p class="bottom-loading" v-if="reqData.noMore&&showNoMore">没有更多了</p>
  </div>
</template>

<script>
  import {
    getRowComments,
    saveRowComment,
    getColumnRemind,
    saveColumnRemind,
    getMyColumnRemind
  } from '@/api/system/column'
  import {
    changeRowLock
  } from '@/api/system/system'
  import {
    mapGetters
  } from 'vuex'
  import elTableInfiniteScroll from 'el-table-infinite-scroll'
  export default {
    directives: {
      'el-table-infinite-scroll': elTableInfiniteScroll
    },
    name: 'relate-table-basic',
    computed: {
      ...mapGetters(['routers', 'sidebar']),
      disabledMore() {
        return this.loadingMore || this.reqData.loading || this.reqData.noMore
      },
      reqLoading() {
        return this.reqData.loading
      }
    },
    watch: {
      reqLoading: {
        handler(newValue, oldValue) {
          this.getTotalWidth()
          this.showNoMore = true
          setTimeout(() => {
            this.showNoMore = false
          }, 2000)
        }
      },
      columnFinalData: {
        handler(newValue, oldValue) {
          if (newValue.length != oldValue.length) {
            this.$nextTick(() => {
              // 初始化表格
              this.$refs.tableGrid.doLayout()
            })
          }
        },
        deep: true
      },
    },
    mounted() {
      const resizeObserver = new ResizeObserver(entries => {
        for (let entry of entries) {
          // let width = entry.target.offsetWidth
          let width = 0
          if (width <= 1) {
            let elems = document.getElementsByClassName('my-define-table-toolbar')
            if (elems && elems.length > 0) {
              width = elems[0].offsetWidth - 40
            } else {
              width = this.totalWidth
            }
          } else {
            width = width + 2
          }
          setTimeout(() => {
            this.divStyle.width = width + 'px'
            this.divStyle.display = 'inline-block !important'
          }, 200)
        }
      })
      this.observeQueryElems(resizeObserver)
    },
    props: {
      reqData: {
        type: Object,
        default: () => ({
          tableData: [],
          rightMenuData: [],
          loading: false,
          noMore: false
        })
      },
      columnFinalData: {
        type: Array,
        default: () => ([])
      },
      sceneType: {
        type: Number,
        default: 0
      },
      sceneId: {
        type: Number,
        default: 0
      },
      defineSceneId: {
        type: Number,
        default: 0
      },
      rowStyle: {
        type: Object,
        default: () => ({})
      },
      tableHeight: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        selectionIds: [],
        selectionData: [],
        showRightMenu: false,
        rightClickRow: null,
        divStyle: {
          width: '0px',
          display: 'inline-block'
        },
        loadingMore: false,
        totalWidth: 0,
        tableStyle: {
          width: '100%'
        },
        showNoMore: false,
        moreColumn: true
      }
    },
    created() {
      var that = this;
      that.$bus.$on('CLEARSELECTIONIDS', (data) => {
        if (data == this.defineSceneId) {
          setTimeout(() => {
            that.tableSelectAll([]);
          }, 500)
        }
      })
      this.$nextTick(() => {
        // 初始化表格
        this.getTotalWidth()
      })
    },
    methods: {
      observeQueryElems(resizeObserver) {
        var queryElems = document.querySelector('.el-table__header-wrapper table')
        if (!queryElems || queryElems.length == 0) {
          setTimeout(() => {
            this.observeQueryElems(resizeObserver)
          }, 100)
          return
        }
        resizeObserver.observe(queryElems);
      },
      tableRowClassName({
        row,
        rowIndex
      }) {
        if (row.levelIndex == 1) {
          return 'my-top-row';
        }
        return '';
      },
      getMyFormatValueHtml(scope) {
        var html = ''
        if (scope.row[scope.column.property + '_fileList']) {
          var myValueArray = scope.row[scope.column.property + '_fileList']
          myValueArray.forEach((valueItem) => {
            var i = valueItem.filePath.lastIndexOf('.');
            var lastType = valueItem.filePath.substr(i + 1);
            if (lastType == 'jpg' || lastType == 'png' || lastType == 'gif' || lastType == 'tif') {
              html += '<a class="my-define-table-value tagg-a" target="_blank" href="' + valueItem.filePath +
                '"><img style="width:22px; height:22px" src="' + valueItem.filePath + '"></a>'
            } else if (lastType == 'pptx') {
              html += '<a class="my-define-table-value tagg-a" target="_blank" href="' + valueItem.filePath +
                '"><span style="background:#FD8037; color:#fff; padding:5px 6px;border-radius:6px;">P</span></a>'
            } else if (lastType == 'xlsx') {
              html += '<a class="my-define-table-value tagg-a" target="_blank" href="' + valueItem.filePath +
                '"><span style="background:#2aa515; color:#fff; padding:5px 5px;border-radius:6px;">X</span></a>'
            } else if (lastType == 'docx') {
              html += '<a class="my-define-table-value tagg-a" target="_blank" href="' + valueItem.filePath +
                '"><span style="background:#0E9FE2; color:#fff; padding:5px 4px;border-radius:6px;">W</span></a>'
            } else if (lastType == 'txt') {
              html += '<a class="my-define-table-value tagg-a" target="_blank" href="' + valueItem.filePath +
                '"><span style="background:#BBB; color:#fff; padding:5px 6px;border-radius:6px;">T</span></a>'
            } else {
              html += '<a class="my-define-table-value tagg-a" target="_blank" href="' + valueItem.filePath +
                '">点击下载</a>'
            }

          })
          return html
        }
        if (scope.row[scope.column.property + '_relateList']) {
          var myValueArray = scope.row[scope.column.property + '_relateList']
          myValueArray.forEach((valueItem) => {
            html +=
              '<span style="margin:0 10px 0 0;height:25px;line-height:25px;" class="el-tag el-tag--info el-tag--light">'
            html += valueItem.dataValue
            html += '<i class="el-tag__close el-icon-close"></i>'
            html += '</span>'
          })
          return html
        }
        var myValue = scope.row[scope.column.property]
        html = myValue
        var myColumn = this.columnFinalData.find((x) => {
          return x.name == scope.column.property && (x.formFieldType == 3 || x.formFieldType == 4 || x
            .formFieldType == 5)
        })
        if (myValue && myColumn && myColumn.fieldData && myColumn.fieldData.length >
          0) {
          var myValueArray = myValue.split(',')
          if (myValue.indexOf('[') > -1) {
            myValueArray = eval('(' + myValue + ')')
          }
          if (myValueArray.length > 0) {
            html = ''
            myValueArray.forEach((valueItem) => {
              var myField = myColumn.fieldData.find((field) => {
                return (field.value == valueItem)
              })
              if (myField && myField.bgColor) {
                html += '<span class="my-define-table-value" style="background-color:' + myField.bgColor +
                  '">' + valueItem + '</span>'
              } else {
                html += '<span class="my-define-table-value">' + valueItem + '</span>'
              }
            })
          }
        }
        return html
      },
      //鼠标悬浮当前行触发
      tableRowEnter(row, column, cell, event) {
        row.isHover = true
      },
      //鼠标离开当前行触发
      tableRowLeave(row, column, cell, event) {
        row.isHover = false
      },
      //选中所有行触发
      tableSelectAll(rows) {
        if (!this.$refs.tableGrid) {
          return
        }
        var selection = rows.length > 0;
        var that = this
        this.reqData.tableData.forEach(item => {
          item.isSelected = selection
          that.$refs.tableGrid.toggleRowSelection(item, selection)
        })
        this.getSelectionIds()
      },
      //选中当前行触发
      tableRowSelect(row, value) {
        this.$refs.tableGrid.toggleRowSelection(row, value)
        this.getSelectionIds()
      },
      setTableRowsSelect(rows, value) {
        if (rows.length == 0) {
          this.tableSelectAll(rows)
          return
        }
        this.$refs.tableGrid.clearSelection();
        rows.forEach((row) => {
          row.isSelected = true
          this.$refs.tableGrid.toggleRowSelection(row, value)
        })
        this.getSelectionIds()
      },
      //获取选中数据
      getSelectionIds() {
        this.selectionIds = []
        this.selectionData = []
        this.reqData.tableData.forEach(element => {
          if (!element.isSelected) {
            return true
          }
          if (element.isLocked) {
            return true
          }
          this.selectionData.push(element)
          this.selectionIds.push(element.Id)
        })
        this.$$parent(this, "setSelectionIds", this.selectionIds, this.selectionData)
      },
      isCollapse() {
        return !this.sidebar.opened
      },
      //列宽变化事件
      headerDragend(newWidth, oldWidth, column, event) {
        localStorage.setItem(this.defineSceneId + '_1_' + column.property, newWidth)
        this.$nextTick(() => {
          // 初始化表格
          this.getTotalWidth()
        })
      },
      getColumnWidth(property, type, index) {
        var width = localStorage.getItem(this.defineSceneId + '_' + type + '_' + property)
        var canReset = false
        if (index == 0) {
          if (!width || Number(width) < 0) {
            canReset = true
          }
          if (canReset) {
            width = '200'
            localStorage.setItem(this.defineSceneId + '_1_' + property, width)
          }
        } else if (!width) {
          width = '200'
        }
        var innerWidth = document.body.clientWidth - 300
        if (this.columnFinalData.length - 1 == index && innerWidth > this.totalWidth) {
          // this.moreColumn = true
          // return 'auto'
        } else {
          // this.moreColumn = false
        }
        return width
      },
      moreColumnVisible() {
        var innerWidth = document.body.clientWidth - 300
        return innerWidth > this.totalWidth
      },
      loadTableData() {
        this.loadingMore = true
        setTimeout(() => {
          this.$$parent(this, "doSearch", {
            goNext: true
          })
          this.loadingMore = false
        }, 100)
      },
      getTotalWidth() {
        var totalWidth = 75
        if (this.columnFinalData.length == 0) {
          totalWidth = 0
        }
        this.columnFinalData.forEach((item) => {
          if (!item.visibile) {
            return true
          }
          var width = localStorage.getItem(this.defineSceneId + '_1_' + item.name)
          if (!width) {
            width = '200'
          }
          totalWidth += Number(width)
        })
        this.totalWidth = totalWidth
        this.tableStyle = {
          width: totalWidth + 'px'
        }
      },
      getColumnAlign(item) {
        if (item.formFieldType == 9) {
          return 'right'
        }
        return 'left'
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  .my-right-menu {
    position: absolute;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    background: #ffffff;
    cursor: pointer;
    color: #606266;
    width: 150px;
    border: 1px solid #e4e7ed;
    font-size: 13px;
    z-index: 9999;
    padding: 0 10px;
  }

  .my-right-menu .saas-iconfont {
    color: #409EFF;
  }

  .my-right-sub-menu {
    line-height: 40px;
    padding: 0 10px;
    border-bottom: solid 1px #f0f0f0;
  }

  .my-right-sub-menu:last-child {
    border-bottom: 0px;
  }

  .el-table.root-table .el-table__row td.el-table__cell:first-child {
    border-left: 0px solid #dfe6ec;
    border-right: 1px solid #bbb;
    padding-left: 20px;
  }

  .el-table.root-table .el-table__row td.el-table__cell:last-child {
    border-right: 0px solid #dfe6ec;
  }

  .el-table.root-table.el-table--border {
    background: #f8f8f8;
    border-top-color: #bbb;
    border-right: 1px solid #dfe6ec;
    // border-left: 0.5px;
  }

  .el-table.root-table th.el-table__cell.is-leaf {
    // border-bottom-color: #f8f8f8;
    border-top: 0px solid #dfe6ec;
  }

  .el-table.root-table.el-table--border th.el-table__cell:first-child {
    border-left: 0px solid #dfe6ec;
    border-right: 1px solid #bbb;
    padding-left: 20px;
    // background: #f00;
  }

  .el-table.root-table.el-table--border th.el-table__cell:last-child {
    border-right: 0px !important;
  }

  .el-table.root-table.el-table--border th.el-table__cell.last-column {
    border-right: 0px !important;
  }

  .table-plus-box {
    border: 1px solid #bbb;
    border-left-width: 1px;
    border-top: 0px;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    line-height: 30px;
    padding: 0 0 0 22px;
    background-color: #fff;
    cursor: pointer;
    display: none !important;
    width: 0px;
  }

  .my-comment-item {
    margin: 0 20px 20px 20px;
    border: solid 1px #ccc;
    border-radius: 5px;
    padding: 15px;
    border-top: solid 5px #0079fe;
  }

  .my-comment-line-1 {
    margin-bottom: 10px;
    font-weight: bold;
  }

  .my-comment-line-2 {}

  .my-comment-icon {
    float: left;
    width: 30px;
    height: 30px;
    background-color: #0079fe;
    border-radius: 5px;
    text-align: center;
    cursor: pointer;
  }

  .my-comment-icon .svg-icon {
    width: 18px;
    height: 18px;
    margin-right: 0 !important;
    margin-top: 5px;
    vertical-align: 1px;
  }

  .my-comment-content {
    float: left;
    font-size: 13px;
    width: calc(100% - 40px);
    margin: 0 0 0 5px;
  }

  .my-comment-name {
    margin-bottom: 5px;
    color: #72767b;
  }

  .column-right-fixed {
    // background-color: #409eff;
    cursor: pointer;
    position: absolute;
    right: 20px;
    font-size: 10px;

    .svg-icon {
      vertical-align: -4px;
      width: 17px;
      height: 17px;
    }

    .column-right-number-fixed {
      margin-left: 5px;

      .column-comment-count-number {
        position: absolute;
        left: 0px;
        display: inline-block;
        width: 18px;
        text-align: center;
        color: #fff;
      }

      .svg-icon {
        width: 18px;
        height: 18px;
        vertical-align: -5px;
      }
    }

    .column-right-number-fixed_2 {
      .column-comment-count-number {
        color: #ff7900;
      }

      .svg-icon {
        fill: #ffeddc;
      }
    }

    .column-right-number-fixed_3 {
      .column-comment-count-number {
        color: #037bf3;
      }

      .svg-icon {
        fill: #d4eaff;
      }
    }
  }

  .column-remind-count {
    position: absolute;
    right: 20px;
    cursor: pointer;
  }

  .remind-calendar .el-calendar-table .el-calendar-day {
    height: 40px;
  }

  .remind-calendar .el-calendar__body {
    padding: 12px 0px 35px
  }

  .my-user-icon-bg {
    background-color: #409eff;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    display: inline-block;
  }

  .my-user-icon-name {
    vertical-align: 10px;
    margin-left: 10px;
  }

  .el-form-item--mini .el-form-item__content {}

  .my-form-right-item.el-form-item--mini .el-form-item__content {
    text-align: right;
  }

  .my-user-icon-edit {
    position: absolute;
    right: 0;
  }

  .my-user-icon-edit .el-link {
    font-size: 14px;
  }

  .el-calendar-table td.is-selected {
    background: #1989fa;
    color: #fff;
  }

  .my-view-his {
    position: absolute;
    right: 0;
  }

  .my-view-his .el-link {
    font-size: 14px;
  }

  .bottom-loading {
    text-align: center;
    margin: 5px 0 0 0;
    font-size: 12px;
  }

  // .el-table--border th.el-table__cell.gutter:last-of-type{
  //   border: 0px;
  //   padding: 0;
  //   width: 0px !important;
  //   display: none !important;
  // }
  .el-table.root-table.el-table--border {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    background-color: #fff;
    border-left: 1px solid #bbb;
    border-right: 1px solid #bbb;
  }

  .el-calendar.remind-calendar .el-calendar__header {
    padding: 12px 0;
  }

  .my-remind-dialog {
    .el-dialog__header {
      padding: 0;
    }

    .el-dialog__body {
      padding: 10px;
    }
  }

  .my-lock-column {
    position: absolute;
    top: 0px;
    left: 0;

    .svg-icon {
      width: 1rem;
      height: 1rem;
      vertical-align: 0;
    }
  }

  .el-extend-span {
    position: absolute;
    right: 0px;
    top: 50%;
    margin-top: -13px;

    .svg-icon {
      width: 12px;
      height: 12px;
      cursor: pointer;
    }
  }

  .el-table.root-table .el-table__fixed::before {
    height: 0px;
  }

  .el-table.root-table .el-table__empty-block {
    border-left: 0px solid #dfe6ec;
    border-right: 0px solid #dfe6ec;
    border-bottom: 1px solid #dfe6ec;
  }

  .el-table__fixed-body-wrapper {
    border-right: 1px solid #dfe6ec;
  }

  .my-define-table-value {
    padding: 1px 5px;
    border-radius: 5px;
    margin-right: 5px;
  }

  a.my-define-table-value {
    color: #0079fe;

    :hover {
      text-decoration: underline;
    }
  }

  // .el-table.root-table.el-table--border th.is-leaf.el-table__cell:first-child{
  //   border-top-left-radius: 10px;
  // }
  // .el-table.root-table.el-table--border th.is-leaf.el-table__cell:last-child{
  //   border-top-right-radius: 10px;
  // }
</style>
